import { createRouter, createWebHistory } from 'vue-router'
import { getToken } from '../utils/cookie'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/oj/login',
      name: 'login',
      component: () => import('@/views/Login.vue')
    },
    {
      path:'/',
      redirect:'/oj/login',
    },
    {
      path: '/oj/layout',
      name: 'layout',
      component: () => import('@/views/Layout.vue'),
      children: [
        {
          path: 'question',
          name: 'question',
          component: () => import('@/views/Question.vue')
        },
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue')
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('@/views/UpdateExam.vue')
        },
        {
          path: 'exam',
          name: 'exam',
          component: () => import('@/views/Exam.vue')
        }
      ]
    },
  ]
})

// 全局前置守卫,在访问登录页面时做一些处理.
router.beforeEach((to, from, next) => {
  //在cookie拿到token说明已经登陆过,如果token过期cookie中token还是存在的.
  //但是却无法判断token是否已经过期,因为并不知道redis当中的数据是否存在.
  //按道理来说,token过期需要重新登录,但是此处无法判断,所以需要在响应拦截器上处理token过期的情况.
  if (getToken()) {  
    /* has token*/
    if (to.path === '/oj/login') {
      next({ path: '/oj/layout/cuser' })
    } else {
      next()
    }
  } else {
    if (to.path !== '/oj/login') {
      next({path:'/oj/login'})
    } else {
      next()
    }
  }
})


export default router
